# 批量替换页眉中的内容
import re
from docx import Document
import os  # 用于获取目标文件所在路径
from docx.oxml.ns import qn # 设置字体
from win32com.client import Dispatch, DispatchEx


def get_filelist(dir):
    filelist = []
    for home, dirs, files in os.walk(dir):
        for filename in files:
            # 文件列表。包含完整路径
            filelist.append(os.path.join(home, filename))
            # 文件名列表，只包含文件名
            # filelist.append(filename)
    return filelist


def doc2docx(input_file, output_file):
    # print(input_file)
    # print(output_file)
    wdFormatdocx = 12
    #     word = Dispatch('Word.Application')
    word = DispatchEx('Word.Application')  # 启动独立进程
    # word.displayalerts=0
    word.visible = 1
    try:
        doc = word.Documents.Open(input_file)
        doc.SaveAs(output_file, FileFormat=wdFormatdocx)
        doc.Close()
    except Exception as e:
        print(e)
    word.Quit()


path = input('==>请输入文件夹的绝对路径：').replace(" ", "")  # 去除输入的空格
old_value = input('==>请输入页眉表格中需要替换的内容：')
new_value = input('==>请输入页眉表格中替换的新内容：')

filelist = get_filelist(path)
docx_filelist = []
notDoclist = []
for file in filelist:
    if file.endswith(".doc"):  # 排除文件夹内的其它干扰文件，只获取".doc"后缀的word文件
        docx_file = file.replace('.doc', '.docx')
        doc2docx(file, docx_file)
        os.remove(file)  # 删除源文件
        print(file + '>>docx  转换完成!')
        docx_filelist.append(docx_file)
    else:
        notDoclist.append(file)
        msg = '未发现.doc文件！！'
print('>>>>>共成功转换文件%s个!' % len(docx_filelist))

newfilelist = docx_filelist + notDoclist
count = 0

for file in newfilelist:
    try:
        # 创建 Doc对象
        Doc = Document(file)
        # 获取第一节
        section = Doc.sections[0]
        # 获取第一节中的页眉
        header = section.header
        # 获取页眉中的表格
        tables = header.tables
        # 获取页眉中的第一个表格
        table = tables[0]
        # 获取表格第一行中的单元格
        # for row_cells in table.rows[0]
        # 获取表格第二行中的单元格
        # row_cells=table.rows[1].cells
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    if old_value in paragraph.text:  # 单元格的内容
                        paragraph.text = paragraph.text.replace(old_value, new_value)
                        # 正则匹配汉字，验证输入内容是否为汉字
                        model = re.compile(u'[\u4e00-\u9fa5]')
                        match = model.search(new_value)
                        for run in paragraph.runs:
                            # 输入的是汉字时
                            if match:
                                run.font.name = u'仿宋'
                                run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋')
                            # 输入的是非汉字时
                            else:
                                # 将单元格内容按照new_value进行切片
                                rest = run.text.split(new_value)
                                run.text = ''
                                for text in rest[:-1]:
                                    # 将切片的两个字符串重新添加到单元格段落中
                                    run = paragraph.add_run(text=text)
                                    run.font.name = u'仿宋'
                                    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋')
                                    run = paragraph.add_run(new_value)
                                    run.font.name = 'Times New Roman'
                                    run._element.rPr.rFonts.set(qn('w:ascii'), 'Times New Roman')
                            count += 1
                            Doc.save(file)  # 存放在原文件夹
                        print(file + '修改完成')
    except Exception as e:
        if type(e) == IndexError:
            print(file, '>>>没有页眉！！')
        elif type(e) == ValueError:
            print(file, '>>>不是word文件！！')
print('>>>>>共检索到%s个文件；' % len(filelist),
      '共%s个文件替换完成！' % count + '\n' + '>>>>>所有文件存放在【 %s 】文件夹！' % path)
